/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-03-22 09:38:17
 * @LastEditors: voanit
 * @LastEditTime: 2022-03-22 11:53:45
 */
/* eslint-disable react/prop-types */
import React, { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'

export default function Item({ todo }) {
  const dispatch = useDispatch()

  const [isEdit, setIsEdit] = useState(false)
  const [name, setName] = useState(false)
  const targetRef = useRef(null)
  useEffect(() => {
    //  表单聚焦
    isEdit && targetRef.current.focus()
  }, [isEdit])
  return (
    <li
      key={todo.id}
      className={[todo.isDone ? 'completed' : '', isEdit ? 'editing' : ''].join(
        ' '
      )}
      // className={'editing'}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={todo.isDone}
          onChange={() => {
            dispatch({
              type: 'todo/changUpdate',
              payload: { id: todo.id, isDone: !todo.isDone },
            })
          }}
        />
        <label
          onDoubleClick={() => {
            ///* 实现双击==显示编辑表单 */
            setIsEdit(true)
            /*表单显示内容 */
            setName(todo.name)
          }}
        >
          {todo.name}
        </label>
        <button
          className="destroy"
          onClick={() => {
            /* 根据id删除数据==数据是从仓库中来的 */
            dispatch({
              type: 'todo/del',
              payload: todo.id,
            })
          }}
        />
      </div>
      <input
        onBlur={() => setIsEdit(false)}
        onKeyUp={(e) => {
          if (e.keyCode === 13) {
            dispatch({
              type: 'todo/update',
              payload: {
                id: todo.id,
                name: name,
              },
            })
            setName('')
            setIsEdit(false)
          }
        }}
        className="edit"
        ref={targetRef}
        onChange={(e) => {
          setName(e.target.value)
        }}
        value={name}
      />
    </li>
  )
}
